<template>
  <div class="order-management-container">
    <!-- 搜索筛选区 -->
    <div class="filter-card">
      <el-form :model="filterForm" inline>
        <!-- 基础信息 -->
        <el-form-item label="订单ID">
          <el-input v-model.number="filterForm.oid" placeholder="订单ID" clearable @keyup.enter="handleSearch"
            style="width: 100px;" />
        </el-form-item>

        <el-form-item label="客户ID">
          <el-input v-model.number="filterForm.cid" placeholder="客户ID" clearable style="width: 80px;" />
        </el-form-item>

        <el-form-item label="产品ID">
          <el-input v-model.number="filterForm.pid" placeholder="产品ID" clearable style="width: 70px;" />
        </el-form-item>

        <!-- 日期范围 -->
        <el-form-item label="下单日期">
          <el-date-picker v-model="filterForm.orderDateRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 190px;" />
        </el-form-item>

        <el-form-item label="预计交付">
          <el-date-picker v-model="filterForm.etaRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 190px;" />
        </el-form-item>

        <!-- 价格范围 -->
        <el-form-item label="价格范围">
          <el-input-number v-model="filterForm.minPrice" placeholder="最低价" :min="0" :precision="2"
            style="width: 130px;" />
          <span style="margin: 0 5px;">-</span>
          <el-input-number v-model="filterForm.maxPrice" placeholder="最高价" :min="0" :precision="2"
            style="width: 130px;" />
        </el-form-item>

        <!-- 状态筛选 -->
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" clearable placeholder="选择状态" style="width: 100px;">
            <el-option label="待激活" :value="0" />
            <el-option label="生产中" :value="1" />
            <el-option label="已送达" :value="2" />
            <el-option label="已结算" :value="3" />
          </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetFilters" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <el-table :data="tableData" v-loading="loading" border stripe highlight-current-row style="width: 100%">
        <el-table-column prop="oid" label="订单ID" width="110" sortable align="center" />
        <el-table-column prop="cid" label="客户ID" width="100" sortable align="center" />
        <el-table-column prop="pid" label="产品ID" width="100" sortable align="center" />

        <el-table-column prop="price" label="单价(元)" width="80" align="right">
          <template #default="{ row }">
            {{ formatPrice(row.price) }}
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" width="80" align="center" />

        <el-table-column prop="totalAmount" label="总价(元)" width="120" sortable align="right">
          <template #default="{ row }">
            {{ formatPrice(row.totalAmount) }}
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="orderDate" label="下单日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.orderDate) }}
          </template>
        </el-table-column>

        <el-table-column prop="eta" label="预计交付" width="120">
          <template #default="{ row }">
            {{ formatDate(row.eta) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" :icon="Edit" type="primary">
              编辑
            </el-button>
            <el-button size="small" @click="handleDetail(row)" :icon="View">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
<!-- 替换原有的 el-pagination -->
<!-- 分页控件 - 改为游标分页 -->
<!-- 分页控件 - 游标分页 -->
<div class="pagination-section">
      <el-button 
        :disabled="!hasPrevPage || loading" 
        @click="loadPrevPage"
        v-if="hasPrevPage"
      >
        ← 上一页 
      </el-button>
      
      <el-button 
        :disabled="!hasNextPage || loading" 
        @click="loadNextPage"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '下一页 →' }}
      </el-button>
 
      <span class="page-info" v-if="tableData.length  > 0">
        当前显示 {{ tableData.length  }} 条记录 
        <span v-if="!hasNextPage">- 已加载全部</span>
      </span>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单信息" width="50%" @closed="resetEditForm">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item label="订单ID" prop="oid">
          <el-input v-model="editForm.oid" disabled />
        </el-form-item>

        <el-form-item label="客户ID" prop="cid">
          <el-input v-model.number="editForm.cid" />
        </el-form-item>

        <el-form-item label="产品ID" prop="pid">
          <el-input v-model.number="editForm.pid" />
        </el-form-item>

        <el-form-item label="单价(元)" prop="price">
          <el-input-number v-model="editForm.price" :min="0" :precision="2" />
        </el-form-item>

        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="editForm.quantity" :min="1" />
        </el-form-item>

        <el-form-item label="总价(元)" prop="totalAmount">
          <el-input-number v-model="editForm.totalAmount" :min="0" :precision="2" />
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="待激活" :value="0" />
            <el-option label="生产中" :value="1" />
            <el-option label="已送达" :value="2" />
            <el-option label="已结算" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="下单日期" prop="orderDate">
          <el-date-picker v-model="editForm.orderDate" type="datetime" placeholder="选择日期" format="YYYY-MM-DD-HH"
            value-format="YYYY-MM-DD-HH" />
        </el-form-item>

        <el-form-item label="预计交付" prop="eta">
          <el-date-picker v-model="editForm.eta" type="datetime" placeholder="选择日期" value-format="YYYY-MM-DD-HH" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗2 -->
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="60%">
      <el-descriptions :column="2" border>
        <!-- 客户信息（始终显示） -->
        <el-descriptions-item label="客户昵称*">{{ detailData.customer?.name || '无' }}</el-descriptions-item>
        <el-descriptions-item label="客户公司">{{ detailData.customer?.company || '无' }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ detailData.customer?.phone || '无' }}</el-descriptions-item>

        <!-- 产品基本信息（始终显示） -->
        <el-descriptions-item label="产品名称*">{{ detailData.product?.name || '无' }}</el-descriptions-item>
        <el-descriptions-item label="产品价格">{{ formatPrice(detailData.product?.price) }}</el-descriptions-item>
        <el-descriptions-item label="叉型">
          {{ detailData.product?.sidefork === 1 ? '四面叉' : '二面叉' }}
        </el-descriptions-item>
        <el-descriptions-item label="板材类型">
          {{ detailData.product?.panel_Leg === 0 ? '板条-原木' : '胶合板-多层板' }}
        </el-descriptions-item>
        <el-descriptions-item label="定制类型">
          {{ detailData.product?.customize === 0 ? '二手' : '定制' }}
        </el-descriptions-item>

        <!-- 仅定制产品显示技术规格 -->
        <template v-if="detailData.product?.customize === 1">
          <!-- 二面叉专属内容 -->
          <template v-if="detailData.product?.sidefork === 0">
            <el-descriptions-item label="底部拉秤">
              {{ detailData.product?.t_bottomlayer === 0 ? '无' : '有' }}
            </el-descriptions-item>
            <el-descriptions-item label="腿布局">
              {{
                detailData.product?.t_leglayout === 0 ? '无' :
                detailData.product?.t_leglayout === 1 ? '三条腿' :
                  detailData.product?.t_leglayout === 2 ? '四条腿' : '未知'
              }}
            </el-descriptions-item>
          </template>

          <!-- 四面叉专属内容 -->
          <template v-else-if="detailData.product?.sidefork === 1">
            <el-descriptions-item label="结构类型">
              {{
                detailData.product?.f_structure === 'N' ? '无' :
                detailData.product?.f_structure === 'A' ? 'A型结构' : 'B型结构'
              }}
            </el-descriptions-item>
            <el-descriptions-item label="垫块高度">
              {{ detailData.product?.f_blockheight || 0 }} cm
            </el-descriptions-item>
          </template>

          <!-- 通用技术规格（无论哪种叉型都显示） -->
          <el-descriptions-item label="板翼">
            {{ detailData.product?.tf_boardwing || 0 }} cm
          </el-descriptions-item>
        </template>

        <!-- 备注（始终显示） -->
        <el-descriptions-item label="备注" :span="2">
          <el-input v-model="detailData.remark" type="textarea" :rows="2" readonly resize="none"
            :placeholder="detailData.remark ? '' : '无备注信息'" />
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>



  </div>
</template>
 

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Refresh, Edit, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { 
  customer_ListWithFiltersAPI, 
  order_ListWithFiltersAPI, 
  order_updateAPI, 
  product_ListWithFiltersAPI 
} from '@/api/api'

const router = useRouter()

// 详情对话框相关 
const detailDialogVisible = ref(false)
const detailData = ref({
  oid: '',
  cid: '',
  pid: '',
  price: 0,
  quantity: 0,
  totalAmount: 0,
  status: 0,
  orderDate: '',
  eta: '',
  remark: '',
  customer: {
    company: '',
    name: '',
    phone: ''
  },
  product: {
    name: '',
    sidefork: 0,
    panel_leg: 0,
    customize: 0,
    t_bottomlayer: 0,
    t_leglayout: 0,
    tf_boardwing: 0,
    f_structure: 'N',
    f_blockheight: 0,
    price: 0,
  }
})

// 组件状态 
const loading = ref(false)
const tableData = ref([])
const nextCursor = ref(null)
const cursorStack = ref([])
const hasNextPage = ref(true)
const hasPrevPage = ref(false)

// 筛选表单 
const filterForm = reactive({
  oid: null,
  cid: null,
  pid: null,
  orderDateRange: [],
  etaRange: [],
  minPrice: null,
  maxPrice: null,
  status: null 
})

// 编辑对话框相关 
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  oid: null,
  cid: null,
  pid: null,
  price: null,
  quantity: 1,
  totalAmount: null,
  status: null,
  orderDate: null,
  eta: null,
  remark: ''
})

// 自动计算总价 
watch(
  () => [editForm.price, editForm.quantity], 
  ([newPrice, newQty]) => {
    const price = parseFloat(newPrice) || 0 
    const qty = parseInt(newQty) || 0 
    editForm.totalAmount = parseFloat((price * qty).toFixed(2))
  },
  { immediate: true }
)

// 表单验证规则 
const editFormRules = {
  cid: [{ required: true, message: '请输入客户ID', trigger: 'blur' }],
  pid: [{ required: true, message: '请输入产品ID', trigger: 'blur' }],
  price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 构建请求参数
const buildParams = (cursor = null) => {
  const params = {
    cursor: cursor,
    limit: 10,
    oid: filterForm.oid, 
    cid: filterForm.cid, 
    pid: filterForm.pid, 
    status: filterForm.status, 
    minPrice: filterForm.minPrice, 
    maxPrice: filterForm.maxPrice  
  }

  // 处理日期范围 
  if (filterForm.orderDateRange?.length === 2) {
    params.startOrderDate = filterForm.orderDateRange[0] 
    params.endOrderDate = filterForm.orderDateRange[1] 
  }

  if (filterForm.etaRange?.length === 2) {
    params.startEta = filterForm.etaRange[0] 
    params.endEta = filterForm.etaRange[1] 
  }

  // 清理空值参数 
  Object.keys(params).forEach(key => {
    if (params[key] === null || params[key] === '' || params[key] === undefined) {
      delete params[key]
    }
  })

  return params 
}

// 处理分页响应
const handlePageResponse = (data) => {
  tableData.value = data.data 
  nextCursor.value = data.nextCursor  
  hasNextPage.value = data.hasNext 
  hasPrevPage.value = cursorStack.value.length > 0
}

// 加载数据（带过滤条件）
const loadData = async (cursor = null) => {
  loading.value = true
  try {
    const params = buildParams(cursor)
    const response = await order_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data) 
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '获取订单数据失败')
    }
  } catch (error) {
    ElMessage.error('数据加载失败：' + error.message) 
  } finally {
    loading.value = false 
  }
}

// 加载第一页
const loadFirstPage = async () => {
  cursorStack.value = []
  await loadData(null)
}

// 加载下一页 
const loadNextPage = async () => {
  if (!nextCursor.value || loading.value) return
  
  loading.value = true
  try {
    if (nextCursor.value) {
      cursorStack.value.push(nextCursor.value) 
    }

    const params = buildParams(nextCursor.value)
    const response = await order_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data) 
      ElMessage.success('下一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error('加载下一页失败：' + error.message) 
  } finally {
    loading.value = false
  }
}

// 加载上一页 
const loadPrevPage = async () => {
  if (cursorStack.value.length <= 1) {
    await loadFirstPage()
    return 
  }

  loading.value = true 
  try {
    cursorStack.value.pop() 
    const prevCursor = cursorStack.value[cursorStack.value.length - 1] || null

    const params = buildParams(prevCursor)
    const response = await order_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data) 
      ElMessage.success('上一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error('加载上一页失败：' + error.message) 
  } finally {
    loading.value = false 
  }
}

// 处理搜索 
const handleSearch = async () => {
  await loadFirstPage()
}

// 重置筛选条件 
const resetFilters = () => {
  Object.keys(filterForm).forEach(key => {
    if (key === 'orderDateRange' || key === 'etaRange') {
      filterForm[key] = []
    } else {
      filterForm[key] = null 
    }
  })
  loadFirstPage()
}

// 查看订单详情 
const handleDetail = async (row) => {
  try {
    loading.value = true 
    detailDialogVisible.value = true 

    // 初始化详情数据 
    detailData.value = {
      oid: row.oid, 
      cid: row.cid, 
      pid: row.pid, 
      price: row.price, 
      quantity: row.quantity, 
      totalAmount: row.totalAmount, 
      status: row.status, 
      orderDate: row.orderDate, 
      eta: row.eta, 
      remark: row.remark || '',
      customer: { company: '', name: '', phone: '' },
      product: { ...detailData.value.product }
    }

    // 并行获取客户和产品详情 
    const [customerRes, productRes] = await Promise.all([ 
      customer_ListWithFiltersAPI({ cid: row.cid, limit: 1 }),
      product_ListWithFiltersAPI({ pid: row.pid, limit: 1 })
    ])
    
    // 更新客户信息 
    if (customerRes.data?.data?.[0]) {
      detailData.value.customer = {
        ...detailData.value.customer, 
        ...customerRes.data.data[0] 
      }
    }

    // 更新产品信息 
    if (productRes.data?.data?.[0]) {
      detailData.value.product = {
        ...detailData.value.product, 
        ...productRes.data.data[0] 
      }
    }

  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error(`获取详情失败: ${error.message}`) 
    detailDialogVisible.value = false 
  } finally {
    loading.value = false 
  }
}

// 编辑订单 
const handleEdit = (row) => {
  Object.assign(editForm, {
    oid: row.oid, 
    cid: row.cid, 
    pid: row.pid, 
    price: row.price, 
    quantity: row.quantity, 
    totalAmount: row.totalAmount, 
    status: row.status, 
    orderDate: row.orderDate, 
    eta: row.eta, 
    remark: row.remark || ''
  })
  editDialogVisible.value = true 
}

// 提交编辑表单 
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate() 

    const response = await order_updateAPI(editForm)

    if (response.code === 200) {
      ElMessage.success(response.message || '订单更新成功')
      editDialogVisible.value = false 

      // 更新本地数据 
      const index = tableData.value.findIndex(item => item.oid === editForm.oid) 
      if (index !== -1) {
        tableData.value[index] = { ...tableData.value[index], ...editForm }
      }
    } else {
      ElMessage.error(response?.message || '订单更新失败')
    }
  } catch (error) {
    console.error('更新订单出错:', error)
    ElMessage.error(error.message || '请求异常')
  }
}

// 重置编辑表单 
const resetEditForm = () => {
  editFormRef.value?.resetFields() 
}

// 辅助方法：格式化价格 
const formatPrice = (price) => {
  return price ? Number(price).toFixed(2) : '0.00'
}

// 辅助方法：格式化日期 
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.split('T')[0] 
}

// 辅助方法：获取状态文本 
const getStatusText = (status) => {
  const statusMap = {
    0: '待激活',
    1: '生产中',
    2: '已送达',
    3: '已结算',
  }
  return statusMap[status] || '未知状态'
}

// 辅助方法：获取状态标签类型 
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'primary',
    3: 'info',
  }
  return typeMap[status] || ''
}

// 初始化加载 
onMounted(() => {
  loadFirstPage()
})
</script>
 
<style scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
  margin-right: 15px;
}
</style>